package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.notice;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.notice.NoticeBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.NoticeExcelEn;
import com.xiaoxu.intranetweb.util.CustomAnnotateUtil;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

@CrossOrigin()
@RestController
@RequestMapping(value = "/notice")
public class NoticeController {
    @Autowired
    private NoticeBu NoticeBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    //查询公告表控制层
    @GetMapping("/getNotice")
    public SzResult getNotice(@RequestParam(required = false) String page,
                              @RequestParam(required = false) String pageSize,
                              @RequestParam(required = false) String title,
                              @RequestParam(required = false) String startTime,
                              @RequestParam(required = false) String endTime,
                              HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return NoticeBu.getNotice(page, pageSize, title, startTime, endTime, token, plantId);

    }

    //    查询公告详情
    @PermissionCheck("noticeDetail_getNoticeDetail")
    @GetMapping("/getNoticeDetail")
    public SzResult getNoticeDetail(@RequestParam String id, HttpServletRequest request) throws Exception {
            return NoticeBu.getNoticeDetail(id);
    }

    //添加公告表控制层
    @PermissionCheck("notice_addNotice")
    @PostMapping("/addNotice")
    public SzResult addNotice(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        String ShortContent = jsonObject.getString("shortContent");
        String plantId = request.getHeader("Plant-Id");
        return NoticeBu.addNotice(title, content, ShortContent, token, plantId);
    }

    //删除公告表控制层
    @PermissionCheck("notice_deleteNotice")
    @GetMapping("/deleteNotice")
    public SzResult deleteNotice(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return NoticeBu.delNotice(id, token, plantId);
    }

    //修改公告表控制层
    @GetMapping("/updateNotice")
    @PermissionCheck("notice_updateNotice")
    public SzResult updateNotice(@RequestParam String id,
                                 @RequestParam(required = false) String title,
                                 @RequestParam(required = false) String content,
                                 @RequestParam(required = false) String shortContent,
                                 @RequestParam(required = false) String creater, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return NoticeBu.updateNotice(id, title, content, shortContent, creater, token, plantId);
    }

    //    上传文件接口
    @PostMapping("/upload")
//    @PermissionCheck("file_upload")
    public SzResult upload(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String connId, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String token = request.getHeader("Authorization");
        return NoticeBu.uploadFile(file, connId, token);
    }

    //    下载文件接口
    @GetMapping("/download")
    public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            SysFiles sysFiles = NoticeBu.downloadFile(fileId);
            Path path = Paths.get(sysFiles.getFilePath() + sysFiles.getId() + "." + sysFiles.getFileType());
            String fileName = sysFiles.getFileName();
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }

    //    删除文件接口
    @GetMapping("/deleteFile")
    @PermissionCheck("file_deleteFile")
    public SzResult deleteFile(@RequestParam("fileId") String fileId, HttpServletRequest request) throws Exception {
        try {
            return NoticeBu.deleteFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    //    预览文件接口
    @GetMapping("/previewFile")
    @PermissionCheck("file_previewFile")
    public SzResult previewFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        try {
            Path path = NoticeBu.previewFile(fileId);
            if (path == null) {
//               无文件
                return SzResult.error("无文件或改文件类型暂不支持预览");
            }
//            根据path拿到文件数据
            InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(path.toString())));
//            转base64
            OutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            String base64 = Base64.getEncoder().encodeToString(((ByteArrayOutputStream) outputStream).toByteArray());
//            关闭流
            outputStream.flush();
            outputStream.close();
            inputStream.close();
//            返回数据
            return SzResult.success(base64);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error("预览失败，文件库内未找到文件资源");
        }
    }


    /**
     * 导出公告
     */
    @PostMapping("/exportExcel")
    public void balanceEnquiryExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        String plantId = null;
//        if (token !=null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);

        String title = null;
        if (form.get("title") != null && !form.get("title").equals("null")) {
            title = form.get("title").toString();
        }
        Future<List<NoticeExcelEn>> listFuture = NoticeBu.exportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, plantId, title);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<NoticeExcelEn> noticeExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "公告";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), NoticeExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("公告")
                .doWrite(noticeExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}
